<template>
  <div class="wrap wrap_coupon_list">
    <div class="coupon_list">
      <a class="coupon_item"
          :href="'/pages/coupon-detail/main?wx_openid=' + openid + '&codeId=' + item.code_id"
          v-for="item in listData"
          :key="item.code_id"
          :class="{disabled: !item._isActive}">
        <div class="aside">
          <img src="/static/img/bg_yhq.png" alt="" class="coupon_bg">
          <span class="text">&yen;{{item.face_value}}</span>
        </div>
        <div class="content">
          <div class="title">{{item.name}}</div>
          <div class="desc">{{item._isActiveTime ? '有效期：至' : '已过期：有效期至'}}{{item._time}}</div>
          <div class="btn_em orange" :class="{none: !item._isActive}">立即使用</div>
          <div class="iconfont icon-zsinto"></div>
        </div>
      </a>
    </div>
  </div>
</template>

<script>
import fly from '@/utils/fly'
import { getOpenid } from '@/utils/login'
import { formatTime } from '@/utils/index'
import { reportData } from '@/utils/report'

export default {
  data () {
    return {
      listData: [],
      hasNext: true,
      canLoadMore: true,
      pageStart: 0,
      pageSize: 4,
      openid: 'openid'
    }
  },
  computed: { },
  methods: {
    async getList () {
      this.canLoadMore = false
      let openid = await getOpenid()
      let url = `Coupon/myList?wx_openid=${openid}&limit=${this.pageStart},${this.pageStart + this.pageSize}`
      let res = await fly.post(url)
      if (res && res.code === 200 && res.data) {
        res.data.list.forEach(item => {
          item._time = formatTime(new Date(item.end_time * 1000))
          item._time = item._time.slice(0, 10)
          item._isActiveTime = item.end_time >= (+new Date() / 1000)
          item._isActive = item._isActiveTime && item.is_used !== 1
        })
        this.listData = this.listData.concat(res.data.list)
        this.pageStart += this.pageSize
        this.hasNext = res.data.page.totalcount > this.pageStart
      } else if (res && res.code === 404) {
        wx.showToast({
          title: `你还没有优惠券`,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: `数据异常${res ? ('(' + res.code + ')') : ''}`,
          icon: 'none'
        })
      }
      this.canLoadMore = true
    }
  },
  async onLoad () {
    // 重置参数
    this.listData = []
    this.pageStart = 0

    wx.showLoading({
      title: '加载中'
    })
    await this.getList()
    wx.hideLoading()

    wx.setNavigationBarTitle({
      title: '优惠券'
    })

    this.openid = await getOpenid()

    reportData({
      funcx: '我的-优惠券',
      keyx: ''
    })
  },
  onPullDownRefresh () {},
  onReachBottom () {
    if (this.hasNext && this.canLoadMore) {
      this.getList()
    }
  }
}
</script>

<style lang="scss">
  @import './coupon-list.scss';
</style>
